// run: $exec < input
#include <iostream>
#include <queue>
#include <cstring>

int const maxn = 100007;
int const maxm = 200007;
int head[maxn], end[2 * maxm], next[2 * maxm];
int in[maxn];
int alloc = 2;
int n, m;

void add_edge(int u, int v)
{
	end[alloc] = v; next[alloc] = head[u]; head[u] = alloc++;
	in[v]++;
}

void init()
{
	alloc = 2;
	std::memset(head, 0, sizeof(head));
	std::memset(in, 0, sizeof(in));
}

int main()
{
	std::ios::sync_with_stdio(false);
	int T; std::cin >> T;
	while (T--) {
		init();
		std::cin >> n >> m;
		for (int i = 0, x, y; i < m; i++) {
			std::cin >> x >> y;
			add_edge(x, y);
		}

		std::priority_queue<int> pq;
		for (int i = 1; i <= n; i++)
			if (!in[i]) pq.push(i);
		long long ans = 0, min = 1 << 30;
		while (!pq.empty()) {
			long long now = pq.top(); pq.pop();
			min = std::min(min, now);
			ans += min;
			for (int p = head[now]; p; p = next[p]) {
				int v = end[p];
				in[v]--;
				if (!in[v]) pq.push(v);
			}
		}
		std::cout << ans << '\n';
	}
}

